import React from 'react';
import { Drawer, Input, message, Modal, Spin, Tag, Tree } from 'antd';
import { Form } from '@ant-design/compatible';
import { connect } from 'dva';
import { PageHeaderLayout, IconButton, PageCard } from '../../components';
import tools from '../../utils';
import Authorized from '../../utils/Authorized';

const basicName = '角色';
const reqApi = 'role';
const formItemLayout = {
  labelCol: { md: 3, xs: 7 },
  wrapperCol: { md: 21, xs: 17 },
};

class page extends React.Component {
  state = {
    loading: false,
    visible: false,
    dialogLoading: false,
    dialogTitle: '',
    dialogAction: '',
    editId: 0,
    beforeName: '', // 编辑时记录初始值
    checkedKeys: [], // 树选择的值
  };

  componentDidMount() {
    this.funcGetListData(true);
  }

  // 获取列表数据
  funcGetListData = (getOtherData = false) => {
    this.setState({ loading: true });

    const { props } = this;

    props.dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: 1,
        pageSize: 1000,
        getOtherData,
      },
    }).then(() => this.setState({ loading: false }));
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const dialogAction = record ? 'edit' : 'create';
    this.setState({
      visible: true,
      dialogTitle: tools.funcDlgTitle(basicName, dialogAction),
      dialogAction,
    }, () => {
      const { props } = this;
      if (dialogAction === 'edit') {
        const { name, menus, res } = record;
        const resData = res.split(',');
        props.form.setFieldsValue({ name, menus, res });
        this.setState({
          beforeName: name,
          checkedKeys: resData,
        });
      } else {
        props.form.resetFields();
        this.setState({ checkedKeys: [] });
      }
    });
  };

  // 删除
  funcDelete = (e, id, name) => {
    e.preventDefault();

    Modal.confirm({
      title: '删除？',
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{name}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + "/dele",
          payload: { ids: id },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData(false);
        });
      },
    });
  };

  // 保存
  funcSave = () => {
    const { state } = this;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const model = { ...values };
      const action = state.dialogAction;
      if (action === "edit") {
        model.id = state.editId;
      }

      if (!model.res) {
        message.error('请选择可用功能');
        return;
      }

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/' + action,
        payload: { action, model },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetListData(false);
        }
      });
    });
  };

  // 检查名称是否被占用
  funcCheckName = (_, value) => {
    if (!value) {
      return Promise.reject('请输入' + basicName + '名称');
    }

    const { state } = this;
    if (state.dialogAction === 'edit' && value === state.beforeName) {
      return Promise.resolve();
    }

    const { props } = this;
    if (props[reqApi].names.indexOf(value) >= 0) {
      return Promise.reject('这个' + basicName + '名称已经存在，请换个名称。');
    }

    return Promise.resolve();
  };

  // 根据树选择的值, 去更新"可见菜单"和"可用资源"的值
  funcUpdateValue = (checkedKeys, halfCheckedKeys) => {
    this.setState({ checkedKeys });

    const menus = [...halfCheckedKeys], res = [];
    checkedKeys.map(key => {
      if (isNaN(key)) res.push(key);
      else menus.push(key);
    });

    const { props } = this;
    props.form.setFieldsValue({
      menus: menus.toString(),
      res: res.toString(),
    });
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;
    const { data, treeData } = props[reqApi];

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          children={(
            <div>
              <Authorized authority={() => tools.funcCheckValid(props, 'create')}>
                <IconButton
                  text={'新增' + basicName}
                  onClick={() => this.funcOpenForm()}
                  style={{ marginRight: 16 }}
                />
              </Authorized>
              <span>{data.length ? '共 ' + data.length + ' 个' + basicName : '暂无' + basicName + ', 请新增'}</span>
              <br />
              <br />
              <Spin spinning={state.loading}>
                {data.map((item) => {
                  const { id, name } = item;
                  return (
                    <Tag
                      key={id}
                      closable={tools.funcCheckValid(props, 'delete')}
                      onClose={(e) => this.funcDelete(e, id, name)}
                      onClick={tools.funcCheckValid(props, 'edit') ? () => {
                        this.setState({ editId: id });
                        this.funcOpenForm(item);
                      } : null}
                      style={{ marginBottom: 8 }}
                    >
                      {name}
                    </Tag>
                  );
                })}
              </Spin>
            </div>
          )}
        />

        <Drawer
          width={window.isMobile ? window.innerWidth : 640}
          title={state.dialogTitle}
          visible={state.visible}
          onClose={() => this.setState({ visible: false })}
          footerStyle={{ textAlign: 'right' }}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ visible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              loading={state.dialogLoading}
              style={{ marginLeft: 8 }}
              onClick={this.funcSave}
            />,
          ]}
        >
          <Form>
            <Form.Item label={basicName + '名称'} {...formItemLayout}>
              {getFieldDecorator('name', {
                rules: [{ required: true, validator: this.funcCheckName }],
              })(<Input maxLength={20} autoFocus />)}
            </Form.Item>

            <Form.Item label='可见菜单' {...formItemLayout} style={{ display: 'none' }}>
              {getFieldDecorator('menus')(<Input />)}
            </Form.Item>

            <Form.Item label='可用资源' {...formItemLayout} style={{ display: 'none' }}>
              {getFieldDecorator('res')(<Input.TextArea />)}
            </Form.Item>

            <Form.Item label='可用功能' {...formItemLayout} style={{ marginBottom: 0 }}>
              <Tree
                checkable
                treeData={treeData}
                showLine={{ showLeafIcon: false }}
                checkedKeys={state.checkedKeys}
                onCheck={(checkedKeys, { halfCheckedKeys }) => {
                  this.funcUpdateValue(checkedKeys, halfCheckedKeys);
                }}
              />
            </Form.Item>
          </Form>
        </Drawer>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ role, menu }) => ({ role, menu }))(page2);
